package com.sptus.controller;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sptus.aop.AppIntercept;
import com.sptus.common.constant.CommonConstant;
import com.sptus.common.core.redis.RedisCache;
import com.sptus.entity.*;
import com.sptus.framework.annotation.AutoLog;
import com.sptus.framework.mqtt.MyMqttClient;
import com.sptus.service.IAppEquipmentService;
import com.sptus.service.IDevDictionariesService;
import com.sptus.service.ISptUserEquipmentService;
import com.sptus.service.ISptUserParentService;
import com.sptus.system.domain.Equipment;
import com.sptus.system.domain.vo.AppInfo;
import com.sptus.system.domain.DevDictionaries;
import com.sptus.util.DevSqlUtil;
import com.sptus.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@Api(tags = "app首页接口")
@RequestMapping("/sys/app/home")
public class AppHomeController {
    @Autowired
    IDevDictionariesService devDictionariesService;
    @Autowired
    IAppEquipmentService equipmentService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private RedisCache redisUtil;

    @Autowired
    ISptUserEquipmentService sptUserEquipmentService;

    @Autowired
    ISptUserParentService sptUserParentService;

    @AppIntercept
    @GetMapping("/getHomeInfo")
    @ApiOperation(value="获取首页展示接口", notes="获取首页展示接口")
    @AutoLog(value = "getHomeInfo",logType = CommonConstant.LOG_TYPE_3,operateType = 1,platformType = 0)
    public Result<Object> getHomeInfo(AppInfo appInfo, SptUser sptUser){
        Result<Object> result = new Result<>();
        Integer id = sptUser.getId();
        // todo 首页真实数据返回
        if (StringUtils.isEmpty(appInfo.getSn())){
            return result.error500("please input sn");
        }
        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSn,appInfo.getSn());

        ArrayList<String> ids = new ArrayList<>();
        LambdaQueryWrapper<SptUserParent> sptUserParentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getUserId,sptUser.getId());
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getState,"1");
        List<HashMap<String,String>> sptUserParents = sptUserParentService.selectListInfo(sptUserParentLambdaQueryWrapper);
        if(sptUserParents.size()>0){
            ids.add(sptUserParents.get(0).get("parent_id"));
        }
        ids.add(sptUser.getId()+"");
        LambdaQueryWrapper<SptUserEquipment> sptUserEquipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserEquipmentLambdaQueryWrapper.eq(SptUserEquipment::getEquipmentId,appInfo.getSn());
        sptUserEquipmentLambdaQueryWrapper.in(SptUserEquipment::getUserId,ids);
        SptUserEquipment sptUserEquipment = sptUserEquipmentService.getBaseMapper().selectOne(sptUserEquipmentLambdaQueryWrapper);
        List<Equipment> equipments = equipmentService.getBaseMapper().selectList(equipmentLambdaQueryWrapper);
        if(StringUtils.isEmpty(sptUserEquipment)){
            result.setResult(new  HashMap<String, Object>());
            return result.ok("Please enter correctly sn");
        }
        if(equipments.get(0).getStatus().equals("2")){
            result.setResult(new  HashMap<String, Object>());
            return result.success("Query success");
        }
        try {
            if(ObjectUtil.isEmpty(redisUtil.getCacheObject(CommonConstant.MSG_LOCK_SN + equipments.get(0).getSn()))){
//                redisUtil.set(CommonConstant.MSG_LOCK_SN + equipments.get(0).getSn(), "1",20);
                redisUtil.setCacheObject(CommonConstant.MSG_LOCK_SN + equipments.get(0).getSn(), "1",20, TimeUnit.SECONDS);
                HashMap<String, String> stringStringHashMap = new HashMap<>();
                stringStringHashMap.put("FORCE_TRAN","0");
                String jsonString = JSONObject.toJSONString(stringStringHashMap);
                if(!ObjectUtil.isEmpty(equipments.get(0).getMac())){
                    MyMqttClient.publishMessage("/"+equipments.get(0).getMac()+"/Rtesttopic",jsonString,1);
//                    stringStringHashMap.put("FORCE_TRAN","2");
//                     jsonString = JSONObject.toJSONString(stringStringHashMap);
//                    MyMqttClient.publishMessage("/"+equipments.get(0).getMac()+"/Rtesttopic",jsonString,1);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        HashMap<String, Object>  devDictionariesHashMap  = devDictionariesService.getHomeInfo(appInfo);
        result.setResult(devDictionariesHashMap);
        return result.success("Query success");
    }



    @AppIntercept
    @GetMapping("/getHistoryData")
    @ApiOperation(value="获取历史数据接口", notes="获取历史数据接口")
    public Result<Object> getHistoryData(AppInfo appInfo,SptUser sptUser) throws ParseException {
        Result<Object> ok=   devDictionariesService.getHistoryData( appInfo, sptUser);
        return ok;
    }

    @AppIntercept
    @GetMapping("/getAllData")
    @ApiOperation(value="获取所有数据接口", notes="获取所有数据接口")
    public Result<Object> getAllData(AppInfo appInfo,SptUser sptUser){
        Result<Object> result = new Result<>();
        Integer id = sptUser.getId();
        long l = System.currentTimeMillis();
        // todo 首页真实数据返回
        if (StringUtils.isEmpty(appInfo.getSn())){
            return result.error500("please enter sn");
        }

        ArrayList<String> ids = new ArrayList<>();
        LambdaQueryWrapper<SptUserParent> sptUserParentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getUserId,sptUser.getId());
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getState,"1");
        List<HashMap<String,String>> sptUserParents = sptUserParentService.selectListInfo(sptUserParentLambdaQueryWrapper);
        if(sptUserParents.size()>0){
            ids.add(sptUserParents.get(0).get("parent_id"));
        }
        ids.add(sptUser.getId()+"");


        LambdaQueryWrapper<SptUserEquipment> sptUserEquipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserEquipmentLambdaQueryWrapper.eq(SptUserEquipment::getEquipmentId,appInfo.getSn());
        sptUserEquipmentLambdaQueryWrapper.in(SptUserEquipment::getUserId,ids);
        SptUserEquipment sptUserEquipment = sptUserEquipmentService.getBaseMapper().selectOne(sptUserEquipmentLambdaQueryWrapper);

        if(StringUtils.isEmpty(sptUserEquipment)){
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            ArrayList<Object> objects = new ArrayList<>();
            stringObjectHashMap.put("all",objects);
            result.setResult(stringObjectHashMap);
            return result.error500("Please enter correctly sn");
        }

        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSn,appInfo.getSn());
        Equipment equipment = equipmentService.getBaseMapper().selectOne(equipmentLambdaQueryWrapper);
        String status = equipment.getStatus();
        if(status.equals("2")){
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
//        stringObjectHashMap.put("cell",allData);
            ArrayList<Object> objects = new ArrayList<>();
            stringObjectHashMap.put("all",objects);
            result.setResult(stringObjectHashMap);
            result.setCode(200);
            return result;
        }

//        try {
//            HashMap<String, String> stringStringHashMap = new HashMap<>();
//            stringStringHashMap.put("FORCE_TRAN","0");
//            String jsonString = JSONObject.toJSONString(stringStringHashMap);
//            MyMqttClient.publishMessage("/"+equipment.getMac()+"/Rtesttopic",jsonString,1);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        LambdaQueryWrapper<DevDictionaries> devDictionariesLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        devDictionariesLambdaQueryWrapper.in(!ObjectUtils.isEmpty(dev.getIds()),DevDictionaries::getId, dev.getIds());
        devDictionariesLambdaQueryWrapper.eq(DevDictionaries::getState, "1");
        devDictionariesLambdaQueryWrapper.orderByAsc(DevDictionaries::getSort);
        List<DevDictionaries> devDictionaries = devDictionariesService.getBaseMapper().selectList(devDictionariesLambdaQueryWrapper);
//        devDictionaries.add();
        //通过字典获取设备数据
        DevDictionaries devDictionariesB1 = new DevDictionaries();
        devDictionariesB1.setCode("BAlone1");
        devDictionariesB1.setRelevanceTable("dev_info_msg6");

        DevDictionaries devDictionariesB2 = new DevDictionaries();
        devDictionariesB2.setCode("BAlone2");
        devDictionariesB2.setRelevanceTable("dev_info_msg6");

        DevDictionaries devDictionariesB3 = new DevDictionaries();
        devDictionariesB3.setCode("BAlone3");
        devDictionariesB3.setRelevanceTable("dev_info_msg6");

        DevDictionaries devDictionariesB4 = new DevDictionaries();
        devDictionariesB4.setCode("BAlone4");
        devDictionariesB4.setRelevanceTable("dev_info_msg6");

        DevDictionaries devDictionariesB5 = new DevDictionaries();
        devDictionariesB5.setCode("BAlone5");
        devDictionariesB5.setRelevanceTable("dev_info_msg6");

        DevDictionaries devDictionariesB6 = new DevDictionaries();
        devDictionariesB6.setCode("BAlone6");
        devDictionariesB6.setRelevanceTable("dev_info_msg6");

        DevDictionaries devDictionariesB7 = new DevDictionaries();
        devDictionariesB7.setCode("BAlone7");
        devDictionariesB7.setRelevanceTable("dev_info_msg6");

        DevDictionaries devDictionariesB8 = new DevDictionaries();
        devDictionariesB8.setCode("BAlone8");
        devDictionariesB8.setRelevanceTable("dev_info_msg6");

        devDictionaries.add(devDictionariesB1);
        devDictionaries.add(devDictionariesB2);
        devDictionaries.add(devDictionariesB3);
        devDictionaries.add(devDictionariesB4);
        devDictionaries.add(devDictionariesB5);
        devDictionaries.add(devDictionariesB6);
        devDictionaries.add(devDictionariesB7);
        devDictionaries.add(devDictionariesB8);

        List<DevDictionaries> devDictionariesList = DevSqlUtil.DevDataSql(devDictionaries, jdbcTemplate, appInfo.getSn());
        Map<String, DevDictionaries> collect = devDictionariesList.stream().collect(Collectors.toMap(DevDictionaries::getCode, Function.identity()));
//        DevDictionaries OPT = collect.get("OPT");
        DevDictionaries SL = collect.get("SL");
        DevDictionaries SB = collect.get("SB");
        DevDictionaries BV = collect.get("BV");
        DevDictionaries VI1 = collect.get("VI1");
        DevDictionaries VI2 = collect.get("VI2");
        DevDictionaries SG = collect.get("SG");
         int bNum=0;
        for (int i = 0; i < 8; i++) {
            DevDictionaries devDictionaries1 = collect.get("BAlone"+(i+1));
            if (!ObjectUtil.isEmpty(devDictionaries1)) bNum+= getBatteryNum(  devDictionaries1.getValue());


        }

//        if(SL.getValue().equals("enable")){
//
//        }
        DevDictionaries devDictionariesBALL = new DevDictionaries();
        devDictionariesBALL.setName("Number of Battery");
        devDictionariesBALL.setCode("BNum");
        devDictionariesBALL.setRelevanceTable("dev_info_msg6");
        devDictionariesBALL.setValue(bNum+"");
        devDictionariesBALL.setState(1+"");
        devDictionariesList.add(devDictionariesBALL);
        if(!StringUtils.isEmpty(SB)){
            if(SB.getValue().equals("Unavliable")){
                SB.setValue(BV.getValue().equals("0")?"Unavliable":"Standby")  ;
            }
        }
        if(!StringUtils.isEmpty(SG)){
            if(SG.getValue().equals("Unavliable")){
                SG.setValue(VI1.getValue().equals("0")&&VI2.getValue().equals("0")?"Unavliable":"Standby")  ;
            }
        }


        devDictionaries=new ArrayList<>();
        devDictionaries.forEach(e->{

            if( e.getCode().equals("SG")){
                e=SG;
            } else if( e.getCode().equals("SB")){
                e=SB;
            }
        });
        long l1 = System.currentTimeMillis();
        long l2 = l1 - l;
        System.out.println(l2);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("all",devDictionariesList);
        result.setResult(stringObjectHashMap);
        return result.success("Query success");
    }
    public int getBatteryNum(String value){
        if(StringUtils.isEmpty(value)){
            return 0;
        }
        int num=0;
        String[] split = value.split(";");
        for (String s : split) {
            boolean b = Integer.parseInt(s) > 0;
            if(b){
                num=1;
                break;
            }

        }
        return  num;
    }
    @AppIntercept
    @GetMapping("/refreshInfo")
    @ApiOperation(value="刷新首页数据", notes="刷新首页数据")
    public Result<Object> refreshInfo(AppInfo appInfo,SptUser sptUser){
        Result<Object> result = new Result<>();
        Integer id = sptUser.getId();
//        LambdaQueryWrapper<SptUser> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        objectLambdaQueryWrapper.eq(SptUser::getId,id);
//        SptUser sptUserInfo = sptUserService.getBaseMapper().selectOne(objectLambdaQueryWrapper);
//        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        equipmentLambdaQueryWrapper.eq(Equipment::getSignBy,sptUser.getId());
//        List<Equipment> equipmentlist = equipmentService.getBaseMapper().selectList(equipmentLambdaQueryWrapper);
//        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
//        stringObjectHashMap.put("equipmentExist",equipmentlist.size()>0);
//        stringObjectHashMap.put("userInfo",sptUserInfo);
//        result.setResult(stringObjectHashMap);
        HashMap<String, Object>  devDictionariesHashMap  = devDictionariesService.getHomeInfo(appInfo);
        result.setResult(devDictionariesHashMap);
        return result.success("Query success");
    }



}
